<template>
  <div class="space-y-2 h-full overflow-y-auto">
    <use-file-select ref="fileRef" class="w-96" />
    <div>
      <a-radio-group type="button" v-model:model-value="lang">
        <a-radio v-for="(value, label) in langDict" :value="value">{{ label }}</a-radio>
      </a-radio-group>
    </div>
    <a-spin :loading="loading" tip="This may take a while..." class="w-96">
      <a-textarea
        :model-value="resultText"
        placeholder="请先选择文件，识别的文字会出现在这里..."
        :auto-size="{
          minRows: 6,
          maxRows: 20,
        }"
      />
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { createWorker } from 'tesseract.js'

const fileRef = ref()
const loading = ref(false)
const resultText = ref('')
const lang = ref('chi_sim')
const href = computed(() => fileRef.value?.href)

const langDict = {
  中文: 'chi_sim',
  英文: 'eng',
}

watch([() => href.value, () => lang.value], async ([e, _lang]) => {
  if (e) {
    loading.value = true
    resultText.value = ''
    await nextTick()
    const worker = await createWorker(_lang)
    const {
      data: { text },
    } = await worker.recognize(e)
    resultText.value = text
    await nextTick()
    await worker.terminate()
    loading.value = false
  } else {
    resultText.value = ''
  }
})
</script>
